$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

$(document).ready(function () {
	var $jqGrid = $("#jqGrid");
	/*$jqGrid.jqGrid({
		url: ctx+'/rfqRequest/rfqRequestAuditList',
        datatype: 'json',
        mtype: 'GET',
		postData:{
			rfqMethod:$("#rfqMethod").val(),
		},
		autowidth:true,
		rownumbers: true,
        colModel: [
				{
					label: 'id',
					name: 'id',
					index: 'ID',
					width: 80,
					key: true,
					hidden:true
				},
				{
				label: '类型',
				name: 'rfqMethod',
				index: 'RFQ_METHOD',
				width: 50,
				align:'center',
				formatter:rfqMethodFormatter
				},
				{
				label:'询价单号',
				name: 'unifiedRfqNum',
				index: 'UNIFIED_RFQ_NUM',
				align:'center',
				width: 120,
				formatter:selectFormatter
				},
			{
				label: '询单标题',
				name: 'title',
				index: 'TITLE',
				align:'center',
				width: 80
			},
			{
				label: '提交人',
				name: 'applicantUsername',
				index: 'APPLICANT_USERNAME',
				align:'center',
				width: 60
			},
			{
				label: '提交时间',
				name: 'applicantTime',
				index: 'APPLICANT_TIME',
				align:'center',
				width: 120
			},
			{
				label: '报价截止时间',
				name: 'quotationEndDate',
				index: 'QUOTATION_END_DATE',
				align:'center',
				width: 120
			},
			{
				label: '审批类型',
				name: 'auditType',
				index: 'AUDIT_TYPE',
				align:'center',
				width: 80,
				formatter: typeFormatter
			},
			{
				label: '状态',
				name: 'showStatus',
				//index: 'STATUS',
				align:'center',
				width: 60,
				formatter: formatStatus
			},
            {
                width: 100,
				label: '操作',
				name: 'operat',
				sortable:false,
                formatter: actFormatter
            }
        ],
        jsonReader: { //映射server端返回的字段
            root: "list",
            rows: "list",
            page: "pageNum",
            total: "pages",
            records: "total"
        },
        prmNames: {
            id: 'id'//请求参数映射，如默认参数为id，实际参数为myId则可在此映射
        },
		postData: {
			status:'0'    //默认查询全部审核状态
		},
        viewrecords: true, // show the current page, data rang and total records on the toolbar
        width: 980,
        height: "100%",
        rowNum: 20,
        rowList: [20, 30, 50, 100],
        sortname: 'APPLICANT_TIME',
        sortorder: 'desc',
        pager: "#jqGridPager",
		caption: "询报价_审批记录表列表"

    });*/

	$jqGrid.jqGrid({
		url: ctx+'/rfqRequest/rfqRequestAuditList',
		datatype: 'json',
		mtype: 'GET',
		postData:{
			rfqMethod:$("#rfqMethod").val(),
		},
		autowidth:true,
		rownumbers: true,
		colModel: [
			{
				label: 'id',
				name: 'requestId',
				index: 'ID',
				width: 80,
				key: true,
				hidden:true
			},
			{
				label: '类型',
				name: 'rfqMethod',
				index: 'RFQ_METHOD',
				width: 50,
				align:'center',
				formatter:rfqMethodFormatter
			},
			{
				label:'询价单号',
				name: 'unifiedRfqNum',
				index: 'UNIFIED_RFQ_NUM',
				align:'center',
				hidden:true,
				width: 120,
				formatter:selectFormatter
			},
            {
                label:'询价单号',
                name: 'ouRfqNum',
                index: 'OU_RFQ_NUM',
                align:'center',
                width: 120,
                formatter:selectFormatter
            },
			{
				label: '询单标题',
				name: 'title',
				index: 'TITLE',
				align:'center',
				width: 80
			},
			{
				label: '提交人',
				name: 'creatorName',
				index: 'APPLICANT_USERNAME',
				align:'center',
				width: 60
			},
			{
				label: '提交时间',
				name: 'startTime',
				index: 'APPLICANT_TIME',
				align:'center',
				width: 120,
                formatter: myTimeFormatter
			},
			{
				label: '报价截止时间',
				name: 'quotationEndDate',
				index: 'QUOTATION_END_DATE',
				align:'center',
				width: 120
			},
			{
				label: '审批类型',
				name: 'billTypeCode',
				index: 'AUDIT_TYPE',
				align:'center',
				width: 80,
				formatter: formatRfqAuditType
			},
			{
				label: '状态',
				name: 'status',
				//index: 'STATUS',
				align:'center',
				width: 60,
				formatter: formatRfqAuditStatus
			},
			{
				label: '事件编号',
				name: 'eventNumber',
				//index: 'STATUS',
				align:'center',
				width: 60,
				hidden:true
			},
			{
				width: 100,
				label: '操作',
				name: 'operat',
				sortable:false,
				formatter: actFormatter
			}
		],
		jsonReader: { //映射server端返回的字段
			root: "list",
			rows: "list",
			page: "pageNum",
			total: "pages",
			records: "total"
		},
		prmNames: {
			id: 'id'//请求参数映射，如默认参数为id，实际参数为myId则可在此映射
		},
		postData: {
			wfType:'2'    //默认查询待审批流程
		},
		viewrecords: true, // show the current page, data rang and total records on the toolbar
		width: 980,
		height: "100%",
		rowNum: 20,
		rowList: [20, 30, 50, 100],
		sortname: 'APPLICANT_TIME',
		sortorder: 'desc',
		pager: "#jqGridPager",
		caption: "询报价_审批记录表列表"

	});

    function formatTitle(cellValue, options, rowObject) {
        return cellValue.substring(0, 50) + "...";
    };
	function actFormatter(cellvalue, options, rawObject) {
		var status = rawObject.showType;   //权限状态
		var type = rawObject.billTypeCode;  //流程类型代码
		var procinstId = rawObject.id;  //流程id
		var procDefType = rawObject.procDefType;  //流程定义类型
		var eventNumber = rawObject.eventNumber;  //事件编号
		var auditStatus1 = rawObject.isAudit;
		var auditStatus2 = rawObject.isDorenAudit;
		var auditStatus3 = rawObject.isResultAudit;
		//var id = rawObject.id;
		//var ps=$('#jqGrid').getCell(id,'status');
		//console.log(ps);
		var detailBtn = '<span class="ml5"><a class="btn btn-sm btn-info re" href="javascript:rfqRequestDetail(\'' + rawObject.requestId +'\'' +'\,'+'\''+ rawObject.rfqMethod+ '\''+'\,'+'\''+ type+'\')"><i class="icon icon-zoom-in"></i>查看</a></span>';
		if('1'==status){  //当前用户角色符合当前审核步骤
			if('RFQ001'==type && '1'==auditStatus1){//创建待审批
				detailBtn = '<span class="ml5">' +
					'<a class="btn btn-sm btn-warning" href="javascript:audit(\'' + rawObject.requestId +'\',\''+ type +'\',\''+ procinstId + '\',\''+ procDefType + '\',\''+ eventNumber +'\')">' +
					'<i class="icon icon-check-sign"></i>审批</a></span>';
			}else if('RFQ002'==type && '1'==auditStatus2){//多轮报价审批
				detailBtn = '<span class="ml5">' +
					'<a class="btn btn-sm btn-warning" href="javascript:audit(\'' + rawObject.requestId +'\',\''+ type +'\',\''+ procinstId + '\',\''+ procDefType + '\',\''+ eventNumber + '\')">' +
					'<i class="icon icon-check-sign"></i>审批</a></span>';
			}else if('RFQ003'==type){//追加供应商审批
				detailBtn = '<span class="ml5">' +
					'<a class="btn btn-sm btn-warning" href="javascript:audit(\'' + rawObject.requestId +'\',\''+ type +'\',\''+ procinstId + '\',\''+ procDefType + '\',\''+ eventNumber + '\')">' +
					'<i class="icon icon-check-sign"></i>审批</a></span>';
			}else if('RFQ004'==type && '1'==auditStatus3 ){//结果待审批
				detailBtn = '<span class="ml5">' +
					'<a class="btn btn-sm btn-warning" href="javascript:audit(\'' + rawObject.requestId +'\',\''+ type +'\',\''+ procinstId +  '\',\''+ procDefType + '\',\''+ eventNumber +'\')">' +
					'<i class="icon icon-check-sign"></i>审批</a></span>';
			}
		}
		return detailBtn;
	};

	var $myTab = $('#myTab');
	//搜索按钮点击
	$('button.btnSearch').on('click',function(){
		jqGridReload();
	});

	//标签页切换
	$myTab.find('[data-toggle]').on('shown.zui.tab', function(e) {
		var $activeTab = $(e.target);
		//表单重置
		var $activeContent = $($activeTab.attr('href'));
		//$activeContent.find('.searchFormTab')[0].reset();
        $.placeholder();
		//状态重置
		var $lis = $activeContent.find('.show-data li');
		$lis.removeClass('active');
		//默认为全部状态激活
		$lis.eq(0).addClass('active');
		//数据重新加载
		jqGridReload();

        getTotal($lis);//数据统计
	});

	//状态页切换
	$('div.tab-content').on('click','.navbar-nav a',function(){
		var $this = $(this);
		var $parent = $this.parent();
		$parent.addClass('active');
		$parent.siblings().removeClass('active');
		$parent.closest('ul').siblings().find('li').removeClass('active');
		jqGridReload();

		/*var $lis = $('.show-data li');
		getTotal($lis);//数据统计*/
	});

	function jqGridReload(params){
		//选择的模式
		var $activeTab = $myTab.find('.active a');
		var rfqMethod = $activeTab.data('method')||'';
		//选择的状态以及表单
		var $activeContent = $($activeTab.attr('href'));
		var type = $activeContent.find('.navbar-nav .active a').attr('data-type')||'';
		var unifiedRfqNum = $("input[name='unifiedRfqNum']").val() ;
		var title = $("input[name='title']").val() ;
		//表单id
		//var formId= $activeContent.find('.searchFormTab')[0].requestId;
		var params = {rfqMethod:rfqMethod,wfType:type,unifiedRfqNum:unifiedRfqNum,title:title};
		//var postData = $.extend(form2Json(formId),params);
		$jqGrid.jqGrid('setGridParam', {
			postData: params,
			page: 1
		}).trigger("reloadGrid");
	}
});

/**
 * 审核操作按钮
 * @param requestId   询单id
 * @param gaId 审核记录id
 * @param type  审核类型
 */
function audit(requestId,type,procinstId,procDefType,eventNumber) {
	location.href = ctx+"/rfqRequest/rfqRequestDetail?id=" + requestId + "&auditType=" + type + "&procinstId=" +procinstId + "&procDefType=" + procDefType +"&eventNumber=" +eventNumber;
}

/**
 * 询单编号链接跳转
 */
function selectFormatter(cellvalue, options, rawObject) {
	var id = rawObject.requestId;
	if('RAQ'==rawObject.rfqMethod){
		return "<a class='blue' target='_blank' href='"+ctx+"/rfqRequest/rfqRequestDetail?id="+id+"' >"+cellvalue+"</a>";
	}else if('DAC'==rawObject.rfqMethod){
		return "<a class='blue' target='_blank' href='"+ctx+"/dacReverseAuction/reverseAuctionDetail?id="+id+"' >"+cellvalue+"</a>";
	}

}

function rfqRequestDetail(id,rfqMethod,auditStatus) {

	if('RAQ'==rfqMethod){
		location.href = ctx+"/rfqRequest/rfqRequestDetail?id=" + id+"&auditStatus="+ auditStatus;
	}else if('DAC'==rfqMethod){
		location.href = ctx+"/dacReverseAuction/reverseAuctionDetail?id=" + id + "&auditStatus=" + auditStatus;
	}

}
if('RAQ'==$("#rfqMethod").val()){

}

/**
 * 类型格式化
 */
function rfqMethodFormatter(cellvalue, options, rawObject) {
	var result = '';
	if('RAQ'==cellvalue){
		result = '<span class="label label-warning">询价</span>';
	}else if('DAC'==cellvalue){
		result = '<span class="label label-primary">反向</span>';
	}else{
		result = '<span class="label label-danger">未知</span>';
	}
	return result;
}

/**
 * 状态格式化
 */
/*function formatStatus(cellvalue, options, rawObject) {
	var result = '';
	var type = rawObject.auditType;
	var auditStatus1 = rawObject.isAudit;
	var auditStatus2 = rawObject.isDorenAudit;
	var auditStatus3 = rawObject.isResultAudit;
	//当前用户角色符合当前审核步骤，且审核状态为“进入审核状态”时，显示未审批
	if('1'==cellvalue && ('1'==auditStatus1 || '1'==auditStatus2 || '1'==auditStatus3)){
		result = '未审批';
	}else if('0'==cellvalue  && ('1'==auditStatus1 || '1'==auditStatus2 || '1'==auditStatus3)){
		result = '等待其他人审批';
	}else{
		if('1'==type){      //创建审批
			if('2'==auditStatus1){
				result = '已通过';
			}else if('3'==auditStatus1){
				result = '审核失败';
			}else{
				result = '未知';
			}
		}else if('2'==type){   //多轮报价审批
			if('2'==auditStatus2){
				result = '已通过';
			}else if('3'==auditStatus2){
				result = '审核失败';
			}else{
				result = '未知';
			}
		}else if('3'==type){    //结果审批
			if('2'==auditStatus3){
				result = '已通过';
			}else if('3'==auditStatus3){
				result = '审核失败';
			}else{
				result = '未知';
			}
		}else{
			result = '审批类型未知';
		}

	}
	return result;
}*/

//数据统计
function getTotal($lis){
    $.get(ctx+'/rfqRequest/rfqRequestAuditDataStat',{},function(data){
        var staticDatas = {};
        var dataObj=data.obj;
        $.each(data.obj,function(i,d){
            staticDatas[i] = d;
        });
        $lis.each(function(){
            var $a = $(this).find('a');
            $a.find('strong').text('('+(staticDatas[$a.data('type')]||0)+')');
        });
    },'json');
}

$(function(){//页面初始化加载统计数据
    //状态重置
    var $lis = $('.show-data li');
    getTotal($lis);
})

typeList=function (data){
   $("#rfqMethod").val(data);
	if('RAQ'==data||''==data){
		$("#jqGrid").jqGrid('setLabel', 3,"询价单号");
		$("#jqGrid").jqGrid('setLabel', 4,"询价标题");
		$("#jqGrid").jqGrid('setCaption',"询报价_审批记录表列表");
	}else if('DAC'==data){
		$("#jqGrid").jqGrid('setLabel', 3,"竞价单号");
		$("#jqGrid").jqGrid('setLabel', 4,"竞价标题");
		$("#jqGrid").jqGrid('setCaption',"反向竞价_审批记录表列表");
	}
};

function myTimeFormatter(cellvalue, options, rawObject) {
    //补0操作
    function getzf(num){
        if(parseInt(num) < 10){
            num = '0'+num;
        }
        return num;
    }

    function getMyDate(str){
        var oDate = new Date(str),
            oYear = oDate.getFullYear(),
            oMonth = oDate.getMonth()+1,
            oDay = oDate.getDate(),
            oHour = oDate.getHours(),
            oMin = oDate.getMinutes(),
            oSen = oDate.getSeconds(),
            oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay) +' '+ getzf(oHour) +':'+ getzf(oMin) +':'+getzf(oSen);//最后拼接时间
        return oTime;
    };
    return getMyDate(cellvalue);
}